// 游戏状态
const gameState = {
    money: 100,
    selectedPlot: null,
    plots: [],
    inventory: {},
    isDrought: false // 干旱状态
};

// 作物数据
const crops = {
    '胖猫': {
        name: '胖猫',
        growthTime: 30, // 秒
        baseValue: 25,
        image: 'pictures/胖猫.jpg',
        seedPrice: 10
    },
    '叮咚鸡': {
        name: '叮咚鸡',
        growthTime: 45, // 秒
        baseValue: 40,
        image: 'pictures/叮咚鸡.jpg',
        seedPrice: 15
    },
    '瓢仓': {
        name: '瓢仓',
        growthTime: 60, // 秒
        baseValue: 60,
        image: 'pictures/瓢仓.jpg',
        seedPrice: 20
    }
};

// DOM元素
const moneyElement = document.getElementById('money');
const farmPlotsElement = document.getElementById('farm-plots');
const harvestButton = document.getElementById('harvest-btn');
const notificationElement = document.getElementById('notification');
const marketItemsElement = document.getElementById('market-items');
// 拖拽元素
let waterImg, fertilizeImg;

// 初始化游戏
function initGame() {
    // 获取DOM元素
    waterImg = document.getElementById('water-img');
    fertilizeImg = document.getElementById('fertilize-img');
    
    // 清空原有数组和UI元素，防止重复添加
    gameState.plots = [];
    farmPlotsElement.innerHTML = '';
    
    // 创建6个农田格子
    for (let i = 0; i < 6; i++) {
        const plot = {
            id: i,
            crop: null,
            plantedTime: null,
            waterLevel: 0,
            fertilized: false,
            ready: false,
            withered: false,
            needsWater: false,
            needsFertilizer: false,
            bubbleTimeout: null
        };
        gameState.plots.push(plot);

        const plotElement = document.createElement('div');
        plotElement.className = 'farm-plot';
        plotElement.id = `plot-${i}`;
        plotElement.innerHTML = `<p>空地</p>`;
        plotElement.addEventListener('click', () => selectPlot(i));
        
        // 为农田格子添加拖拽事件监听
        plotElement.addEventListener('dragover', (e) => handleDragOver(e, i));
        plotElement.addEventListener('dragleave', (e) => handleDragLeave(e, i));
        plotElement.addEventListener('drop', (e) => handleDrop(e, i));
        
        farmPlotsElement.appendChild(plotElement);
    }

    // 绑定购买种子按钮事件
    document.querySelectorAll('.buy-btn').forEach(button => {
        button.addEventListener('click', (e) => {
            const seedItem = e.target.closest('.seed-item');
            const seedType = seedItem.dataset.seed;
            const price = parseInt(seedItem.dataset.price);
            buySeed(seedType, price);
        });
    });

    // 绑定拖拽事件
    initDragAndDrop();

    // 绑定收获按钮事件
    harvestButton.addEventListener('click', harvestCrop);

    // 随机触发干旱事件
    setInterval(() => {
        if (Math.random() < 0.1) { // 10%几率
            gameState.isDrought = true;
            showNotification('干旱来临！浇水获得额外奖励！', 5000);
            setTimeout(() => {
                gameState.isDrought = false;
                showNotification('干旱结束', 3000);
            }, 20000); // 干旱持续20秒
        }
    }, 60000); // 每分钟检查一次

    // 随机显示农作物需求气泡
    setInterval(showRandomCropNeeds, 15000);

    // 更新游戏状态
    setInterval(updateGame, 1000);
}

// 初始化拖拽功能
function initDragAndDrop() {
    // 浇水拖拽
    waterImg.addEventListener('dragstart', (e) => {
        e.dataTransfer.setData('action', 'water');
        
        // 使用自定义小尺寸图像作为拖拽图标
        const canvas = document.createElement('canvas');
        canvas.width = 50;
        canvas.height = 50;
        const ctx = canvas.getContext('2d');
        const img = new Image();
        img.src = 'pictures/可乐.png';
        img.onload = () => {
            ctx.drawImage(img, 0, 0, 50, 50);
        };
        
        e.dataTransfer.setDragImage(canvas, 25, 25);
    });

    // 施肥拖拽
    fertilizeImg.addEventListener('dragstart', (e) => {
        e.dataTransfer.setData('action', 'fertilize');
        
        // 使用自定义小尺寸图像作为拖拽图标
        const canvas = document.createElement('canvas');
        canvas.width = 50;
        canvas.height = 50;
        const ctx = canvas.getContext('2d');
        const img = new Image();
        img.src = 'pictures/麦当劳.png';
        img.onload = () => {
            ctx.drawImage(img, 0, 0, 50, 50);
        };
        
        e.dataTransfer.setDragImage(canvas, 25, 25);
    });
}

// 处理拖拽经过农田
function handleDragOver(e, plotIndex) {
    e.preventDefault();
    const plot = gameState.plots[plotIndex];
    const plotElement = document.getElementById(`plot-${plotIndex}`);
    
    // 只有有作物且未枯萎的农田才能接受拖拽
    if (plot.crop && !plot.withered) {
        e.dataTransfer.dropEffect = 'copy';
        plotElement.classList.add('drag-over');
    } else {
        e.dataTransfer.dropEffect = 'none';
    }
}

// 处理拖拽离开农田
function handleDragLeave(e, plotIndex) {
    const plotElement = document.getElementById(`plot-${plotIndex}`);
    plotElement.classList.remove('drag-over');
}

// 处理拖拽放置
function handleDrop(e, plotIndex) {
    e.preventDefault();
    const plotElement = document.getElementById(`plot-${plotIndex}`);
    plotElement.classList.remove('drag-over');
    
    const action = e.dataTransfer.getData('action');
    const plot = gameState.plots[plotIndex];
    
    // 根据拖拽的物品执行不同操作
    if (action === 'water') {
        if (plot.crop && !plot.withered && !plot.ready) {
            waterCrop(plotIndex);
        }
    } else if (action === 'fertilize') {
        if (plot.crop && !plot.fertilized && !plot.withered && !plot.ready) {
            fertilizeCrop(plotIndex);
        }
    }
}

// 随机显示农作物需求
function showRandomCropNeeds() {
    // 遍历所有种植了作物且未枯萎未成熟的农田
    gameState.plots.forEach((plot, index) => {
        if (plot.crop && !plot.withered && !plot.ready) {
            // 清除之前的气泡
            clearTimeout(plot.bubbleTimeout);
            
            // 随机决定是否显示气泡
            if (Math.random() < 0.5) {
                // 随机决定需要什么
                let needType;
                if (!plot.fertilized) {
                    needType = Math.random() < 0.5 ? 'water' : 'fertilize';
                } else {
                    needType = 'water';
                }
                
                // 更新状态
                plot.needsWater = needType === 'water';
                plot.needsFertilizer = needType === 'fertilize';
                
                // 显示气泡
                const plotElement = document.getElementById(`plot-${index}`);
                let bubble = plotElement.querySelector('.speech-bubble');
                
                if (!bubble) {
                    bubble = document.createElement('div');
                    bubble.className = 'speech-bubble';
                    plotElement.appendChild(bubble);
                }
                
                bubble.textContent = needType === 'water' ? '我要喝可乐!' : '我要吃麦当劳!';
                setTimeout(() => {
                    bubble.classList.add('show');
                }, 100);
                
                // 设置气泡消失的定时器
                plot.bubbleTimeout = setTimeout(() => {
                    bubble.classList.remove('show');
                    plot.needsWater = false;
                    plot.needsFertilizer = false;
                }, 5000);
            }
        }
    });
}

// 更新游戏状态
function updateGame() {
    // 更新每个作物的生长状态
    gameState.plots.forEach((plot, index) => {
        if (plot.crop && !plot.withered && !plot.ready) {
            const crop = crops[plot.crop];
            const now = Date.now();
            const elapsedTime = (now - plot.plantedTime) / 1000; // 转换为秒
            
            // 计算生长时间，如果施肥则减半
            const growthTime = plot.fertilized ? crop.growthTime * 0.5 : crop.growthTime;
            
            // 计算进度
            let progress = (elapsedTime / growthTime) * 100;
            // 增加浇水的进度
            progress += plot.waterLevel;
            
            // 限制最大进度为100%
            progress = Math.min(progress, 100);
            
            // 更新进度条
            const plotElement = document.getElementById(`plot-${index}`);
            const progressBar = plotElement.querySelector('.progress');
            if (progressBar) {
                progressBar.style.width = `${progress}%`;
            }
            
            // 检查是否成熟
            if (progress >= 100) {
                plot.ready = true;
                updatePlotUI(index);
                showNotification(`${plot.crop}已经成熟，可以收获了！`, 3000);
            }
            // 检查是否枯萎（超时2倍生长时间未收获）
            else if (elapsedTime > growthTime * 2) {
                plot.withered = true;
                updatePlotUI(index);
                showNotification(`${plot.crop}已经枯萎了！`, 3000);
            }
        }
    });

    // 更新金币显示
    moneyElement.textContent = gameState.money;
    
    // 更新按钮状态
    updateButtonStates();
}

// 选择农田格子
function selectPlot(index) {
    // 取消之前选中的格子
    if (gameState.selectedPlot !== null) {
        const prevPlotElement = document.getElementById(`plot-${gameState.selectedPlot}`);
        prevPlotElement.classList.remove('selected');
    }
    
    // 选中当前格子
    gameState.selectedPlot = index;
    const plotElement = document.getElementById(`plot-${index}`);
    plotElement.classList.add('selected');
    
    // 更新按钮状态
    updateButtonStates();
}

// 更新按钮状态
function updateButtonStates() {
    const selectedPlot = gameState.selectedPlot !== null ? gameState.plots[gameState.selectedPlot] : null;
    
    // 只更新收获按钮状态
    harvestButton.disabled = !selectedPlot || !selectedPlot.crop || !selectedPlot.ready || selectedPlot.withered;
}

// 购买种子
function buySeed(seedType, price) {
    if (gameState.money >= price) {
        // 检查是否有空地
        const emptyPlotIndex = gameState.plots.findIndex(plot => !plot.crop);
        
        if (emptyPlotIndex !== -1) {
            // 确保作物类型在crops对象中存在
            if (!crops[seedType]) {
                console.error(`未知的种子类型: ${seedType}`);
                showNotification(`错误: 未知的种子类型`, 2000);
                return;
            }
            
            // 扣除金币
            gameState.money -= price;
            moneyElement.textContent = gameState.money;
            
            // 种植作物
            const plot = gameState.plots[emptyPlotIndex];
            plot.crop = seedType;
            plot.plantedTime = Date.now();
            plot.waterLevel = 0;
            plot.fertilized = false;
            plot.ready = false;
            plot.withered = false;
            
            // 更新UI
            updatePlotUI(emptyPlotIndex);
            
            // 显示通知
            showNotification(`成功种植了${seedType}`, 2000);
            
            // 自动选择该地块
            selectPlot(emptyPlotIndex);
            
            console.log(`种植成功: ${seedType} 在土地 ${emptyPlotIndex}`);
        } else {
            showNotification('没有空余的农田！', 2000);
        }
    } else {
        showNotification('金币不足！', 2000);
    }
}

// 更新农田UI
function updatePlotUI(index) {
    const plot = gameState.plots[index];
    const plotElement = document.getElementById(`plot-${index}`);
    
    if (!plot || !plotElement) return; // 防止空引用错误
    
    if (!plot.crop) {
        plotElement.innerHTML = `<p>空地</p>`;
    } else {
        const crop = crops[plot.crop];
        
        if (!crop) {
            console.error(`找不到作物数据: ${plot.crop}`);
            return;
        }
        
        if (plot.withered) {
            plotElement.innerHTML = `
                <div class="crop-img-container">
                    <img src="${crop.image}" alt="${plot.crop}" style="opacity: 0.5;">
                </div>
                <p>${plot.crop} (枯萎)</p>
                <button class="action-btn" onclick="clearPlot(${index})">清除</button>
            `;
        } else if (plot.ready) {
            plotElement.innerHTML = `
                <div class="crop-img-container">
                    <img src="${crop.image}" alt="${plot.crop}">
                </div>
                <p>${plot.crop} (成熟)</p>
                <div class="progress-bar"><div class="progress" style="width: 100%;"></div></div>
            `;
        } else {
            // 计算当前进度
            const now = Date.now();
            const elapsedTime = (now - plot.plantedTime) / 1000;
            const growthTime = plot.fertilized ? crop.growthTime * 0.5 : crop.growthTime;
            let progress = (elapsedTime / growthTime) * 100 + plot.waterLevel;
            progress = Math.min(progress, 99); // 保持在99%以下，让updateGame控制最终100%
            
            plotElement.innerHTML = `
                <div class="crop-img-container">
                    <img src="${crop.image}" alt="${plot.crop}">
                </div>
                <p>${plot.crop} ${plot.fertilized ? '(麦当劳真好吃)' : ''}</p>
                <div class="progress-bar"><div class="progress" style="width: ${progress}%;"></div></div>
            `;
        }
    }
}

// 浇水
function waterCrop(plotIndex) {
    const plot = gameState.plots[plotIndex !== undefined ? plotIndex : gameState.selectedPlot];
    if (!plot || !plot.crop || plot.withered || plot.ready) return;
    
    // 增加成长进度
    const waterBonus = gameState.isDrought ? 20 : 10; // 干旱时浇水效果翻倍
    plot.waterLevel += waterBonus;
    
    // 清除需要水的标记和气泡
    if (plotIndex !== undefined) {
        const plotElement = document.getElementById(`plot-${plotIndex}`);
        const bubble = plotElement.querySelector('.speech-bubble');
        if (bubble) {
            bubble.classList.remove('show');
        }
        clearTimeout(plot.bubbleTimeout);
    }
    plot.needsWater = false;
    
    // 更新UI
    updatePlotUI(plotIndex !== undefined ? plotIndex : gameState.selectedPlot);
    
    // 显示通知
    if (gameState.isDrought) {
        showNotification(`可乐真好喝！干旱期间效果翻倍！+${waterBonus}%成长`, 2000);
    } else {
        showNotification(`可乐真好喝！+${waterBonus}%成长`, 2000);
    }
}

// 施肥
function fertilizeCrop(plotIndex) {
    const plot = gameState.plots[plotIndex !== undefined ? plotIndex : gameState.selectedPlot];
    if (!plot || !plot.crop || plot.fertilized || plot.withered || plot.ready) return;
    
    // 标记为已施肥
    plot.fertilized = true;
    
    // 清除需要肥料的标记和气泡
    if (plotIndex !== undefined) {
        const plotElement = document.getElementById(`plot-${plotIndex}`);
        const bubble = plotElement.querySelector('.speech-bubble');
        if (bubble) {
            bubble.classList.remove('show');
        }
        clearTimeout(plot.bubbleTimeout);
    }
    plot.needsFertilizer = false;
    
    // 更新UI
    updatePlotUI(plotIndex !== undefined ? plotIndex : gameState.selectedPlot);
    
    // 显示通知
    showNotification('麦当劳真好吃！生长速度提升50%', 2000);
}

// 收获
function harvestCrop() {
    if (gameState.selectedPlot === null) return;
    
    const plot = gameState.plots[gameState.selectedPlot];
    if (!plot.crop || !plot.ready || plot.withered) return;
    
    const cropType = plot.crop;
    const crop = crops[cropType];
    
    // 计算收获金额（基础价值，施肥有50%减产）
    const harvestValue = plot.fertilized ? Math.floor(crop.baseValue * 0.5) : crop.baseValue;
    
    // 增加金币
    gameState.money += harvestValue;
    moneyElement.textContent = gameState.money;
    
    // 添加到库存
    if (!gameState.inventory[cropType]) {
        gameState.inventory[cropType] = 0;
    }
    gameState.inventory[cropType]++;
    
    // 重置地块
    plot.crop = null;
    plot.plantedTime = null;
    plot.waterLevel = 0;
    plot.fertilized = false;
    plot.ready = false;
    plot.withered = false;
    
    // 更新UI
    updatePlotUI(gameState.selectedPlot);
    updateMarketUI();
    
    // 显示通知
    showNotification(`成功收获${cropType}！获得${harvestValue}金币`, 2000);
}

// 清除枯萎的作物
function clearPlot(index) {
    const plot = gameState.plots[index];
    if (!plot.withered) return;
    
    // 重置地块
    plot.crop = null;
    plot.plantedTime = null;
    plot.waterLevel = 0;
    plot.fertilized = false;
    plot.ready = false;
    plot.withered = false;
    
    // 更新UI
    updatePlotUI(index);
    
    // 显示通知
    showNotification('清除枯萎作物成功', 2000);
}

// 更新市场UI
function updateMarketUI() {
    marketItemsElement.innerHTML = '';
    
    let hasItems = false;
    
    for (const [cropType, count] of Object.entries(gameState.inventory)) {
        if (count > 0) {
            hasItems = true;
            const crop = crops[cropType];
            
            const marketItem = document.createElement('div');
            marketItem.className = 'market-item';
            marketItem.dataset.crop = cropType;
            marketItem.dataset.price = crop.baseValue;
            marketItem.innerHTML = `
                <img src="${crop.image}" alt="${cropType}">
                <p>${cropType} (${count})</p>
                <p class="price">售价: ${crop.baseValue}金币</p>
            `;
            
            // 绑定点击整个物品就可以卖出
            marketItem.addEventListener('click', () => {
                sellCrop(cropType, crop.baseValue);
            });
            
            marketItemsElement.appendChild(marketItem);
        }
    }
    
    if (!hasItems) {
        marketItemsElement.innerHTML = '<p class="empty-market">库存为空</p>';
    }
}

// 卖出作物
function sellCrop(cropType, price) {
    if (gameState.inventory[cropType] && gameState.inventory[cropType] > 0) {
        // 减少库存
        gameState.inventory[cropType]--;
        
        // 增加金币
        gameState.money += price;
        moneyElement.textContent = gameState.money;
        
        // 更新市场UI
        updateMarketUI();
        
        // 显示通知
        showNotification(`卖出${cropType}成功！获得${price}金币`, 2000);
    }
}

// 显示通知
function showNotification(message, duration = 3000) {
    notificationElement.textContent = message;
    notificationElement.classList.add('show');
    
    setTimeout(() => {
        notificationElement.classList.remove('show');
    }, duration);
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', initGame); 